<?php
namespace backend\controllers;

use common\components\BaseController;
use Yii;
use yii\db\Query;
use \common\helps\tools;
use \common\helps\code;

/**
 * User controller
 */
class PostsController extends BaseController
{

    public $modelClass = 'backend\models\MovieCollege';

    /*
     * 发帖列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionPostsList()
    {
        $model = new \backend\models\Posts();
        $member = new \backend\models\Member();
        $request =$this->request;
        $params = $request->queryParams;
        //$params = $request->bodyParams;
        $total = $model::selectData($params);
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        foreach ($res['data'] as $k => $v){
            $row = $member::findOne(['id' => $v['set_posts_id']]);
            $res['data'][$k]['set_posts_name'] = $row['username'].'/'.$v['set_posts_id'];
        }
        if(!empty($params['excel_download']) && $params['excel_download']>0){
            $tableHeader = ['标题','项目名称','群组','影视学堂id','发帖人','发帖人id','审核状态','备注','收藏人数','点赞人数','创建时间'];
            $data = [];
            foreach ($total as $k => $v){
                //$data[$k]['id'] = $v['id'];
                $data[$k]['title'] = $v['title'];
                $data[$k]['item'] = $v['item'];
                $data[$k]['group'] = $v['group'];
                $data[$k]['movie_id'] = $v['movie_id'];
                $data[$k]['set_posts_name'] = empty($v['set_posts_name'])?'':$v['set_posts_name'];
                $data[$k]['set_posts_id'] = empty($v['set_posts_id'])?'':$v['set_posts_id'];
                $data[$k]['set_posts'] = $data[$k]['set_posts_name'].'/'.$data[$k]['set_posts_id'];
                if($v['status'] == 1){
                    $status = '待审核';
                }elseif($v['status'] == 2){
                    $status = '已拒绝';
                }else{
                    $status = '已通过';
                }
                $data[$k]['status'] = $status;
                $data[$k]['error'] = empty($v['error'])?'':$v['error'];
                $data[$k]['collect_num'] = "'".$v['collect_num']."'";
                $data[$k]['like_num'] = "'".$v['like_num']."'";
                $data[$k]['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
            }
            tools::ToPHPEXECL($tableHeader,$data,'发帖列表');
        }
        return code::success($res);
    }

    /*
     * 添加
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddPosts()
    {
        $model = new \backend\models\Posts();
        $pjoin = new \backend\models\PostsJoin();
        $member = new \backend\models\Member();
        $group = new \backend\models\Group();
        $project = new \backend\models\NewProject();
        $session = Yii::$app->session;
        $request =$this->request;
        $params = $request->bodyParams;
        if(!empty($params)) {
            if ($model->load($params, '')) {
                if ($model->validate()) {
                    $params['admin_id'] = $session->get('user_id');
                    $params['admin_name'] = $session->get('username');
                    $res = $model->saveInfo('create', $params);
                    $data['posts_id'] = $res;
                    $data['group_id'] = !empty($params['group_id'])?$params['group_id']:'';
                    $data['item_id'] = !empty($params['item_id'])?$params['item_id']:'';
                    $data['movie_id'] = !empty($params['movie_id'])?$params['movie_id']:'';
                    $rat = $pjoin->saveInfo($data);
                    if (empty($res->errorInfo) && empty($rat->errorInfo)) {
                        return code::success(true);
                    } else {
                        return code::error('error');
                    }
                } else {
                    $error = array_values($model->getErrors());
                    return code::error('', $error[0][0]);
                }
            }
        }else{
            $data['adminInfo'] = $member->selectData('`id`,`username`,`mobile`,`created_at`',['is_auth' => 2]);
            $data['groupInfo'] = $group->selectDataField(['`id`,`name`']);
            $data['project'] = $project::selectData(['`id`,`title`']);
            return code::success($data);
        }
    }

    /*
     * 审核帖子
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCheckPosts()
    {
        $model = new \backend\models\Posts();
        $notice = new \frontend\models\Notice();
        $task = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $request =$this->request;
        $params = $request->bodyParams;
        $id = $params['id'];
        unset($params['id']);
        if(!empty($params)) {
            $info = $model::findOne(['id' => $id]);
            if(empty($info)){
                return code::error('mistake');
            }
            if($info['status'] == $params['status']){
                return code::success(true);
            }
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $res = $model::saveData($id, $params);
                $ndata = [
                    'member_id' => $info['set_posts_id'],
                    'posts_id' => $info['id'],
                    'type' => 3,
                    'at_member_id' => '',
                    'comment' => '',
                ];
                if($params['status'] == 3){
                    $ndata['check_status'] = 1;

                    $member_info = $member::findOne(['id' => $info['set_posts_id']]);
                    if(empty($member_info)){
                        return code::error('','用户不存在，请联系管理员');
                    }
                    $day = $redis->get('checkPosts'.date('Y-m-d').$member_info['id']);
                    if($day === false){
                        $redis->set('checkPosts' . date('Y-m-d') . $member_info['id'], date('Y-m-d H:i:s'),86400);
                        $task_info = $task::findOne(['id' => 2]);
                        //用户加积分
                        $idata = [
                            'member_id' => $info['set_posts_id'],
                            'task_id' => $task_info['id'],
                            'int' => $task_info['integral'],
                            'type' => 1,
                        ];
                        $rat = $int::addData($idata);

                        $integral = $member_info['integral'] + $task_info['integral'];
                        $addInt = $member::saveData($member_info['id'],['integral' => $integral]);
                        $member_info['integral'] = $integral;
                        $redis->hset('member_info', $member_info['token'], json_encode($member_info));
                    }else{
                        $rat = 1;
                        $addInt = 1;
                    }
                }else{
                    $ndata['check_status'] = 2;
                    $ndata['check_msg'] = $params['error'];

                    $rat = 1;
                    $addInt = 1;
                }
                $row = $notice::addData($ndata);

                if ($res && $row && $rat && $addInt) {
                    $transaction->commit();
                    return code::success(true);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                return $e->getMessage();
            }
        }
    }

    /*
     * 帖子详情
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionPostsDetail()
    {
        $model = new \backend\models\Posts();
        $request =$this->request;
        $params = $request->bodyParams;
        $data = $model::findOneData($params['id']);
        return code::success($data);
    }

    /*
     * 删除发帖
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionDeletePosts()
    {
        $model = new \backend\models\Posts();
        $request =$this->request;
        $params = $request->bodyParams;
        $res = $model::deleteData($params['id']);
        return code::success($res);
    }

    /*
     * 评论列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCommentList()
    {
        $model = new \backend\models\Comment();
        $request =$this->request;
        $params = $request->queryParams;
        //$params = $request->bodyParams;
        $total = $model::selectData($params);
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        foreach ($res['data'] as $k => $v){
            $res['data'][$k]['member_name'] = $v['member_name'].'/'.$v['member_id'];
        }
        if(!empty($params['excel_download']) && $params['excel_download']>0){
            $tableHeader = ['id','内容','原贴标题','帖子id','评论用户','评论用户id','审核状态','拒绝原因','创建时间'];
            $data = [];
            foreach ($total as $k => $v){
                $data[$k]['id'] = $v['id'];
                $data[$k]['comment'] = $v['comment'];
                $data[$k]['title'] = $v['title'];
                $data[$k]['posts_id'] = $v['posts_id'];
                $data[$k]['member_name'] = $v['member_name'];
                $data[$k]['member_id'] = $v['member_id'];
                if($v['status'] == 1){
                    $status = '待审核';
                }elseif($v['status'] == 2){
                    $status = '已拒绝';
                }else{
                    $status = '已通过';
                }
                $data[$k]['status'] = $status;
                $data[$k]['error'] = $v['error'];
                $data[$k]['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
            }
            tools::ToPHPEXECL($tableHeader,$data,'评论列表');
        }
        return code::success($res);
    }

    /*
     * 添加评论
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddComment()
    {
        $model = new \backend\models\Comment();
        $posts = new \backend\models\Posts();
        $member = new \backend\models\Member();
        $request =$this->request;
        $params = $request->bodyParams;
        if(!empty($params)){
//            $memberInfo = $member::findFieldData(['mobile' => $params['mobile']],['`id`']);
//            if(empty($memberInfo)){
//                return code::error('errorMember');
//            }
//            $params['member_id'] = $memberInfo['id'];
//            unset($params['mobile']);
            $res = $model::addData($params);
        }else{
            $res['adminInfo'] = $member->selectData('`id`,`username`,`created_at`',['is_auth' => 2]);
            $res['posts'] = $posts::selectFieldData(['`id`,`title`']);
        }
        return code::success($res);
    }

    /*
     * 评论详情
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCommentDetail(){
        $model = new \backend\models\Comment();
        $request =$this->request;
        $params = $request->bodyParams;
        $data = $model::findOneData($params['id']);
        return code::success($data);
    }

    /*
     * 审核评论
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCheckComment()
    {
        $model = new \backend\models\Comment();
        $posts = new \backend\models\Posts();
        $notice = new \frontend\models\Notice();
        $task = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $request =$this->request;
        $params = $request->bodyParams;
        $id = $params['id'];
        unset($params['id']);
        if(!empty($params)) {
            $minfo = $model::findOne(['id' => $id]);
            if(empty($minfo)){
                return code::error('mistake');
            }
            if($minfo['status'] == $params['status']){
                return code::success(true);
            }
            $pinfo = $posts::findOne(['id' => $minfo['posts_id']]);
            if(empty($pinfo)){
                return code::error('','该评论的帖子已删除');
            }
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $res = $model::saveData($id,$params);
                if($params['status'] == 3) {
                    $ndata = [
                        'member_id' => $pinfo['set_posts_id'],
                        'posts_id' => $pinfo['id'],
                        'type' => 1,
                        'at_member_id' => $minfo['member_id'],
                        'comment' => $minfo['comment'],
                        'check_status' => 1,
                    ];
                    $row = $notice::addData($ndata);
                }else{
                    $row = 1;
                }
                $rdata = [
                    'member_id' => $minfo['member_id'],
                    'posts_id' => $pinfo['id'],
                    'type' => 2,
                    'at_member_id' => '',
                    'comment' => $minfo['comment'],
                ];
                if($params['status'] == 3){
                    $rdata['check_status'] = 1;

                    $member_info = $member::findOne(['id' => $minfo['member_id']]);
                    if(empty($member_info)){
                        return code::error('','用户不存在，请联系管理员');
                    }
                    $day = $redis->get('checkComment'.date('Y-m-d').$member_info['id']);
                    if($day === false){
                        $redis->set('checkComment' . date('Y-m-d') . $member_info['id'], date('Y-m-d H:i:s'),86400);
                        //用户加积分
                        $task_info = $task::findOne(['id' => 3]);
                        $idata = [
                            'member_id' => $minfo['member_id'],
                            'task_id' => $task_info['id'],
                            'int' => $task_info['integral'],
                            'type' => 1,
                        ];
                        $intLog = $int::addData($idata);

                        $integral = $member_info['integral'] + $task_info['integral'];
                        $addInt = $member::saveData($member_info['id'],['integral' => $integral]);
                        $member_info['integral'] = $integral;
                        $redis->hdel('member_info', $member_info['token']);
                        $redis->hset('member_info', $member_info['token'], json_encode($member_info));
                    }else{
                        $intLog = 1;
                        $addInt = 1;
                    }
                }else{
                    $rdata['check_status'] = 2;
                    $rdata['check_msg'] = $params['error'];

                    $intLog = 1;
                    $addInt = 1;
                }
                $rat = $notice::addData($rdata);
                if ($res && $row && $rat && $intLog && $addInt) {
                    $transaction->commit();
                    return code::success(true);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                return $e->getMessage();
            }
        }
    }

    /*
     * 删除评论
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionDeleteComment()
    {
        $model = new \backend\models\Comment();
        $request =$this->request;
        $params = $request->bodyParams;
        $res = $model::deleteData($params['id']);
        return code::success($res);
    }


}
